from lxml import etree

import xmltodict
from django.http import HttpResponse
from rest_framework import serializers
from rest_framework.views import APIView

from jiaozi.base_view import JwtListAPIView
from jiaozi.utils import MmFilter, get_user_id
from money.models import PayRecord
from money.serializers import PayRecordSerializer
from sales.models import ProductSalesOrder
from vip.models import VipSalesOrder


def confirm_pay_record(out_trade_no):
    """
    进行支付订单的确认
    :param out_trade_no: 支付订单号
    """
    pay_record = PayRecord.objects.filter(out_trade_no=out_trade_no).first()
    if not pay_record.is_payed:
        pay_record.is_payed = True
        if pay_record.pay_type == 1:  # VIP 销售
            vip_sales_order = VipSalesOrder.objects.filter(pay_record_id=pay_record.pk).first()
            if not vip_sales_order.is_payed:
                vip_sales_order.is_payed = True
            vip_sales_order.save()
        elif pay_record.pay_type == 2:  # 商品销售
            product_sales_order = ProductSalesOrder.objects.filter(pay_record_id=pay_record.pk).first()
            if not product_sales_order.is_payed:
                product_sales_order.is_payed = True
            if product_sales_order.order_state == 1:
                product_sales_order.order_state = 2
            product_sales_order.save()
        pay_record.save()


class WeChatPayNotifySerializer(serializers.Serializer):
    para = serializers.CharField(required=False)


class WeChatPayNotifyAPIView(APIView):
    authentication_classes = ()
    permission_classes = ()
    serializer_class = WeChatPayNotifySerializer

    def post(self, request):
        res_data = {'xlm': {'return_code': 'SUCCESS', 'return_msg': 'OK'}}
        res_xml = xmltodict.unparse(res_data)

        _xml = request.body
        # 拿到微信发送的xml请求 即微信支付后的回调内容
        xml = str(_xml, encoding="utf-8")
        if not xml:
            return HttpResponse(content=res_xml)
        tree = etree.fromstring(xml)
        # xml 解析
        return_code = tree.find("return_code").text

        try:
            if return_code == 'FAIL':
                # 官方发出错误
                print('支付失败', tree)
            elif return_code == 'SUCCESS':
                # 拿到自己这次支付的 out_trade_no
                out_trade_no = tree.find("out_trade_no").text
                confirm_pay_record(out_trade_no)
        except Exception as e:
            print('支付异常', e)

        return HttpResponse(content=res_xml)


class PayRecordFilter(MmFilter):
    class Meta:
        model = PayRecord
        fields = {
            'out_trade_no': ['exact'],
        }


class PayRecordListView(JwtListAPIView):
    """
    get:
        支付记录的查询，以后只返回支付成功的记录
    """
    serializer_class = PayRecordSerializer
    filterset_class = PayRecordFilter
    queryset = None
    pagination_class = None

    def get_queryset(self):
        user_id = get_user_id(self)
        queryset = PayRecord.objects.filter(user_id=user_id)
        return queryset
